package com.evil.gateway.filter;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.evil.common.core.constant.AppConstant;
import com.evil.common.core.entity.R;
import com.evil.common.core.entity.TokenInfo;
import com.evil.common.core.enums.RCodeEnum;
import com.evil.common.core.util.TokenUtil;
import com.evil.gateway.props.AuthProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 网关认证拦截
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Slf4j
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final TokenUtil tokenUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();

        String requestUuid = UUID.fastUUID().toString(true);

        ServerHttpRequest mutableReqSkip = exchange.getRequest().mutate()
                .header(AppConstant.HEADER_REQUEST_UUID, requestUuid)
                .build();

        // 跳过不需要验证的路径
        if (authProperties.getSkipUrl().stream().anyMatch(e -> e.equals(path)
                || (e.endsWith("/**") && path.startsWith(e.replace("/**", ""))))) {
            ServerWebExchange mutableExchange = exchange.mutate().request(mutableReqSkip).build();
            return chain.filter(mutableExchange);
        }

        String token = exchange.getRequest().getQueryParams().getFirst(AppConstant.TOKEN_KEY);
        token = StringUtils.isBlank(token) ? exchange.getRequest().getHeaders().getFirst(AppConstant.TOKEN_KEY) : token;

        if (StringUtils.isBlank(token)) {
            return unAuth(exchange, "token不能为空");
        }

        TokenInfo tokenInfo;
        try {
            tokenInfo = tokenUtil.getTokenInfo(token);
        } catch (Exception e) {
            return unAuth(exchange, "您当前登录状态失效，请重新登录");
        }

        if (tokenInfo.getUserId() == null) {
            return unAuth(exchange, "您当前登录状态失效，请重新登录");
        }

        ServerHttpRequest mutableReq = exchange.getRequest().mutate()
                .header(AppConstant.HEADER_REQUEST_UUID, requestUuid)
                .header(AppConstant.TOKEN_KEY, token)
                .header(AppConstant.HEADER_USER_ID, tokenInfo.getUserId().toString())
                .header(AppConstant.HEADER_ENTERPRISE_ID, tokenInfo.getEnterpriseId().toString())
                .build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
        return chain.filter(mutableExchange);
    }

    private Mono<Void> unAuth(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, AppConstant.CONTENT_TYPE_JSON);

        String result = JSON.toJSONString(R.error(RCodeEnum.ERROR_UNAUTHENTICATED, message));
        DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));

        return response.writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
